package com.dormms.www.vo;

import com.dormms.www.ContactsGUI;
import com.dormms.www.database.DatabaseConnection;

import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class AddContactDialog extends JDialog {
    private JTextField nameField;
    private JTextField phoneField;
    private JTextField emailField;

    public AddContactDialog(JFrame parent) {
        super(parent, "添加联系人", true);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        gbc.gridx = 0;
        gbc.gridy = 0;
        add(new JLabel("姓名:"), gbc);

        gbc.gridx = 1;
        nameField = new JTextField(20);
        add(nameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        add(new JLabel("电话:"), gbc);

        gbc.gridx = 1;
        phoneField = new JTextField(20);
        add(phoneField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        add(new JLabel("邮箱:"), gbc);

        gbc.gridx = 1;
        emailField = new JTextField(20);
        add(emailField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        JButton addButton = new JButton("添加");
        add(addButton, gbc);

        addButton.addActionListener(e -> addContactToDatabase());

        pack();
        setLocationRelativeTo(parent);
    }

    private void addContactToDatabase() {
        String name = nameField.getText();
        String phone = phoneField.getText();
        String email = emailField.getText();

        if (name.isEmpty() || phone.isEmpty() || email.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段都是必填的。", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String query = "INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setString(1, name);
            pstmt.setString(2, phone);
            pstmt.setString(3, email);
            pstmt.executeUpdate();
            dispose(); // 关闭对话框
            ((ContactsGUI) getParent()).loadContacts(); // 刷新表格
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加联系人时出错。", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
